// 设置公共路径
export const baseUrl = 'https://dingxin.bigchun.com/';

const request = ({
	url,
	method,
	data = {},
	hideLoading
}) => {
	const headers = {
		'content-type': 'application/json',
		'x-requested-with': 'XMLHttpRequest',
		"token": uni.getStorageSync('token') || ''
	};
	data.token = uni.getStorageSync('token') || ''

	// 如果调用接口不明确不显示 loading
	if (!hideLoading) {
		uni.showLoading({
			title: '加载中',
			mask: true
		});
	}

	return new Promise((resolve, reject) => {
		
		uni.request({
			url: (url.substr(0, 4) == 'http') ? url : (baseUrl + url),
			data: data,
			header: headers,
			method: method,
			success: (response) => {
				if (!hideLoading) {
					uni.hideLoading();
				}
				const result = response.data;
				if (result.code == 1) {
					resolve(result)
				}else if(result.code == 401){
					uni.removeStorageSync("token")
				}else {
					uni.showModal({
						title: '',
						content: result.msg || '',
						showCancel:false
					});
					reject(result)
				}
			},
			complete: () => {
				if (!hideLoading) {
					uni.hideLoading();
				}
			},
			fail: (err) => {
				console.log(headers);
				if (!hideLoading) {
					uni.hideLoading();
				}
				uni.showToast({
					title: "请求失败，请重试",
					icon: 'none',
					duration: 1500
				});
				reject(err)
			}
		})

	})
}

export const uploadFile = ({
	url,
	filePath,
	name,
	formData = {},
	hideLoading
}) => {
	const headers = {
		'content-type': 'application/json',
		'x-requested-with': 'XMLHttpRequest',
	};
	formData.token = uni.getStorageSync('token') || ''
	// 如果调用接口不明确不显示 loading
	if (!hideLoading) {
		uni.showLoading({
			title: '加载中',
			mask: true
		});
	}
	url = (url.substr(0, 4) == 'http') ? url : (baseUrl + url)
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url,
			name: name || 'file',
			header: headers,
			filePath: filePath,
			formData:formData,
			success: (response) => {
				if (!hideLoading) {
					uni.hideLoading();
				}
				const result = JSON.parse(response.data)
				if (result.code == 1) {
					resolve(result)
				}else if(result.code == 401){
					uni.removeStorageSync("token")
				}else {
					uni.showModal({
						title: '',
						content: result.msg || '',
						showCancel:false
					});
					reject(result)
				}
			},
			complete: () => {
				if (!hideLoading) {
					uni.hideLoading();
				}
			},
			fail: (err) => {
				console.log(headers);
				if (!hideLoading) {
					uni.hideLoading();
				}
				uni.showToast({
					title: "请求失败，请重试",
					icon: 'none',
					duration: 1500
				});
				reject(err)
			}
		})
	})
}


export default request;